﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;
using System.IO;

namespace ourForm
{
    public partial class ourMainForm : Form
    {
        string email = "";
        public ourMainForm()
        {
            InitializeComponent();
            encryptDecryptToolStripMenuItem.Enabled = false;
            signatureToolStripMenuItem.Enabled = false;
            importFromFileToolStripMenuItem.Enabled = false;
            exportToFileToolStripMenuItem.Enabled = false;
        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            loginToolStripMenuItem.Enabled = false;
            ourAdd_in.frmLogIn f = new ourAdd_in.frmLogIn();
            f.MdiParent = this;
            f.OnLogIn += new ourAdd_in.frmLogIn.logIn_FireMainForm(f_OnLogIn);
            f.EnableMenuItem += new ourAdd_in.frmLogIn.enableMenuItem(f_EnableLoginMenuItem);
            f.Show();

            //this.Enabled = false;            
        }

        void f_EnableLoginMenuItem()
        {
            loginToolStripMenuItem.Enabled = true;
            //throw new NotImplementedException();
        }

        void f_OnLogIn(string Email)
        {
            email = Email;
            BUS.AccountBUS bus = new BUS.AccountBUS();
            AccountDTO dto = bus.GetAccountInfo(email);
            this.Text = dto.Name + "-" + "Email: " + dto.Email;
            encryptDecryptToolStripMenuItem.Enabled = true;
            signatureToolStripMenuItem.Enabled = true;
            importFromFileToolStripMenuItem.Enabled = true;
            exportToFileToolStripMenuItem.Enabled = true ;
            //throw new NotImplementedException();
        }

        private void registerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            registerToolStripMenuItem.Enabled = false;
            ourAdd_in.frmRegister f = new ourAdd_in.frmRegister();
            f.MdiParent = this;
            f.EnableMenuItem+=new ourAdd_in.frmRegister.enableMenuItem(f_EnableRegisterMenuItem);
            f.Show();
        }

        void f_EnableRegisterMenuItem()
        {
            registerToolStripMenuItem.Enabled = true;
        }
        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            editToolStripMenuItem.Enabled = false;
            ourAdd_in.frmUpdate f = new ourAdd_in.frmUpdate();
            f.MdiParent = this;
            f.EnableMenuItem += new ourAdd_in.frmUpdate.enableMenuItem(f_EnableUpdateMenuItem);
            f.Show();
        }

        void f_EnableUpdateMenuItem()
        {
            editToolStripMenuItem.Enabled = true;
            //throw new NotImplementedException();
        }

        private void encryptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmEncrypt f = new frmEncrypt();
            f.MdiParent = this;
            f.Show();
        }

        private void exportToFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BUS.AccountBUS bus= new BUS.AccountBUS();
            AccountDTO account = bus.GetAccountInfo(email);
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "XML file (*.xml)|*xml";
            dlg.FileName= email + ".xml";
           // dlg.CheckFileExists = true;
            string directory = "C:\\AccountInfo";
           if(!System.IO.Directory.Exists(directory))
               System.IO.Directory.CreateDirectory("C:\\AccountInfo");
            dlg.InitialDirectory = "C:\\AccountInfo";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                bus.ExportToXML(dlg.FileName, account);
            }
            
        }

        private void importFromFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BUS.AccountBUS bus = new BUS.AccountBUS();
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "XML file (*xml)|*xml";
            string filePath = "";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.FileName != null)
                {
                   filePath = dlg.FileName;
                   if (bus.ImportFromXML(filePath))
                       MessageBox.Show("Import successfully!");
                   else
                       MessageBox.Show("Import failed!");
                }
            }
          
            
        }

        private void decryptToolStripMenuItem_Click(object sender, EventArgs e)
        {

            frmPassForPrivateKey f = new frmPassForPrivateKey(email);
            f.MdiParent = this;
            f.OnGetKey += new frmPassForPrivateKey.getKey(f_OnGetKey);
            f.Show();
           
        }

        void f_OnGetKey()
        {
            AccountBUS bus = new AccountBUS();
           AccountDTO account=bus.GetAccountInfo(email);
            OpenFileDialog dlg = new OpenFileDialog();
            if(dlg.ShowDialog()==DialogResult.OK)
            {
                if (dlg.FileName != null)
                {
                    // truyen tren file cho bus
                    //bus.GiaiMa()
                    //BUS.OurSymAlgo bus = new BUS.OurSymAlgo();
                    byte[] decryptedBytes = { };
                    decryptedBytes=OurSymAlgo.Decrypt(dlg.FileName,account.PrivateKey);
                    SaveDecryptedFile(decryptedBytes, dlg.FileName);
                }
            }
        }

        void SaveDecryptedFile(byte[] decryptedBytes,string filePath)
        {
            if (File.Exists(filePath) && Path.GetExtension(filePath) == ".enc")
            {
                SaveFileDialog dlg = new SaveFileDialog();
                string directory = "C:\\Decrypted Files";
                if (!System.IO.Directory.Exists(directory))
                    System.IO.Directory.CreateDirectory(directory);
                dlg.InitialDirectory = directory;
                dlg.FileName = Path.GetFileNameWithoutExtension(filePath);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    
                    //
                   
                    try
                    {
                        using (Stream s = File.Create(dlg.FileName))
                        {
                            s.Write(decryptedBytes, 0, decryptedBytes.Length);
                        }
                        MessageBox.Show("File Decrypted Successfully");

                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show(ex.ToString());
                    }
                }
            }
            else 
            {
            }
          

        }

        private void signToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //load form cho NSD gõ password vào để xác thực.
            frmPassForPrivateKey form = new frmPassForPrivateKey(email);

            //sử dụng delegate do form gửi cho main form thông báo đã xác nhận thành công.
            form.OnGetKey += new frmPassForPrivateKey.getKey(f_openSign);

            form.Show();
        }

        //sau khi xác nhận password thành công thì cho phép NSD chọn file bất kì để kí.
        private void f_openSign()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                byte[] data = File.ReadAllBytes(dlg.FileName);
                BUS.AccountBUS bus=new BUS.AccountBUS();
                AccountDTO account=bus.GetAccountInfo(email);
                byte[] signature=BUS.OurRSA.HashAndSign(data,account.PrivateKey);
                using (Stream s=File.Create(dlg.FileName+".sig"))
                {
                    s.Write(signature, 0, signature.Length);
                }
                MessageBox.Show("Signed Data Successful!");
            }
            else
            {

            }
        }

        private void verifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            f_openVerify();
        }

        private void f_openVerify()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                OpenFileDialog dlgOpenFileSign = new OpenFileDialog();
                dlgOpenFileSign.Filter = "sig files (*.sig)|*.sig";
                dlgOpenFileSign.RestoreDirectory = true;
                string fileSignName = "";
                if (dlgOpenFileSign.ShowDialog()==DialogResult.OK)
                {
                    fileSignName = dlgOpenFileSign.FileName;
                }
                else 
                {
                    fileSignName = dlg.FileName + ".sig";
                }

                if (!File.Exists(fileSignName))
                {
                    MessageBox.Show("Not Found Signature");
                    return;
                }
                byte[] data = File.ReadAllBytes(dlg.FileName);
                byte[] signature = File.ReadAllBytes(fileSignName);
                BUS.AccountBUS bus=new BUS.AccountBUS();
                List<AccountDTO> list = bus.GetAllAccountInfo();
                foreach (var item in list)
                {
                    if (BUS.OurRSA.VerifyHash(data, signature, item.PublicKey))
                    {
                        frmAccountInfo form = new frmAccountInfo();
                        form.MdiParent = this;
                        string _info = "";
                        _info += "Name: " + item.Name + "\r\n";
                        _info += "Phone: " + item.Phone + "\r\n";
                        _info += "Email: " + item.Email + "\r\n";
                        _info += "Address: " + item.Address + "\r\n";
                        form._info = _info;
                        form.Show();
                    }
                }
            }
            else
            {

            }
        }
    }
}
